package com.mls.fivedistrict.server.impl;

import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.mls.fivedistrict.dao.ManagerUserMapper;
import com.mls.fivedistrict.pojo.ManagerUser;
import com.mls.fivedistrict.pojo.UserRole;
import com.mls.fivedistrict.server.ManagerUserService;
import com.mls.fivedistrict.server.UserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Five Team
 * @since 2018-07-02
 */
@Service
public class ManagerUserServiceImpl extends ServiceImpl<ManagerUserMapper, ManagerUser> implements ManagerUserService {
    @Autowired
    UserRoleService userRoleService;
    @Autowired
    ManagerUserMapper managerUserMapper;
    @Override
    @Transactional
    public boolean insert(ManagerUser managerUser) {
        Integer insert = managerUserMapper.insert(managerUser);
        List<UserRole> userRoleList = managerUser.getUserRoleList();
        if(null!=userRoleList&&userRoleList.size()>0){
            for(UserRole userRole:userRoleList){
                userRole.setManagerUserId(managerUser.getId());
            }
            userRoleService.insertBatch(userRoleList);
        }
        if(null!=insert&&insert>=1){
            return true;
        }
        return false;
    }

    @Override
    public boolean updateById(ManagerUser managerUser) {
        Integer update = managerUserMapper.updateById(managerUser);
        Wrapper wrapper=Condition.create();
        wrapper.eq("manager_user_id",managerUser.getId());
        //修改前的角色关系
        List before = userRoleService.selectList(wrapper);
        //修改后的角色关系
        List<UserRole> after = managerUser.getUserRoleList();
        //如果有数据先删除
        if(null!=after){
            if(null!=before&&before.size()>0){
                userRoleService.delete(wrapper);
            }
        }
        if(null!=after&&after.size()>0){
            for(UserRole userRole:after){
                userRole.setManagerUserId(managerUser.getId());
            }
            userRoleService.insertBatch(after);
        }
        if(null!=update&&update>=1){
            return true;
        }
        return  false;
    }

    @Override
    public ManagerUser selectById(Serializable id) {
        return managerUserMapper.selectById(id);
    }
}
